//
//  XSJStatusDAL.swift
//  weiBo项目准备
//
//  Created by 鲜世杰 on 16/5/24.
//  Copyright © 2016年 鲜世杰. All rights reserved.
//

import UIKit

class XSJStatusDAL: NSObject {
    
    class func loadData(maxId: Int64, sinceId: Int64, callback: (statuses: [[String: AnyObject]]) -> ()) {
        
        let tempArray = [[String : AnyObject]]()
        let result = checkCacheData(maxId, sinceId: sinceId)
        
        if result.count > 0 {
            
            callback(statuses: result)
            return
            
        }
        
        XSJNetWorkTools.sharedTools.requestStatus(XSJUserAccountViewModel.sharedUserAccount.accessToken!, maxId: maxId, sinceId: sinceId) { (response, error) -> () in
            if error != nil {
                
                print("网络请求异常")
                callback(statuses: tempArray)
                return
                
            }
            
            guard let dic = response as? [String : AnyObject] else {
                
                print("不是一个正确的json格式")
                callback(statuses: tempArray)
                return
                
            }
            guard let statusesArray = dic["statuses"] as? [[String: AnyObject]] else {
                
                print("不是一个正确的json格式")
                callback(statuses: tempArray)
                
                return
            }
            
            XSJStatusDAL.cacheData(statusesArray)
            callback(statuses: statusesArray)
        }
    }
    
    class func checkCacheData(maxId : Int64, sinceId : Int64) -> [[String : AnyObject]]  {
        var sql = "SELECT statusid, status, userid FROM Status\n"
        
        if maxId > 0 {
            sql += "where statusid < \(maxId)\n"
            
        }else {
            
            sql += "where statusid > \(sinceId)\n"
            
            
        }
        
        sql += "and userid = \(XSJUserAccountViewModel.sharedUserAccount.userAccount!.uid)\n"
        sql += "order by statusid desc\n"
        
        sql += "limit 20\n"
        
        let result = SqliteManager.manager.queryResultSetWithSql(sql)
        
        var tempArray = [[String : AnyObject]]()
        
        for value in result {
            
            let stsatus = value["status"]! as! NSData
            
            let statusDic = try! NSJSONSerialization.JSONObjectWithData(stsatus, options: []) as! [String : AnyObject]
            
            tempArray.append(statusDic)
        }
        
        return tempArray
    }
    
    class func cacheData(status: [[String: AnyObject]]) {
        
        let sql = "INSERT INTO STATUS(STATUSID, STATUS, USERID) VALUES(?,?,?)"
        let userid = XSJUserAccountViewModel.sharedUserAccount.userAccount!.uid
        SqliteManager.manager.queue?.inTransaction({ (db, rollback) -> Void in
            
            for value in status {
                
                let statusid = value["id"]!
                
                let statusData = try! NSJSONSerialization.dataWithJSONObject(value, options: [])
                
                let result = db.executeUpdate(sql, withArgumentsInArray: ["\(statusid)", statusData, "\(userid)"])
                
                if result == false {
                    
                    rollback.memory = true
                    
                    break
                    
                }
                
                
            }
            
        })
        
    }
    
    
    class func clearCacheData() {
        let date = NSDate().dateByAddingTimeInterval(-60 * 30)
        
        let dateFormater = NSDateFormatter()
        
        dateFormater.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        dateFormater.locale = NSLocale(localeIdentifier: "en_US")
        
        let dateStr = dateFormater.stringFromDate(date)
        
        let sql = "DELETE FROM STATUS WHERE TIME < '\(dateStr)'"
        
        SqliteManager.manager.queue?.inDatabase({ (db) -> Void in
            
            let result = db.executeUpdate(sql, withArgumentsInArray: nil)
            
            if result {
                
                print("清除缓存成功\(db.changes())")
                
            }else {
                
                print("清除缓存失败")
                
            }
            
            
            
        })
    }
    
    
}
